package com.debao.system.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.debao.common.constant.VipConstants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.enums.OrderStatusEnum;
import com.debao.common.model.TempData;
import com.debao.common.model.WechatTemplateVo;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.utils.KeyGreaterUtil;
import com.debao.common.utils.SecurityUtils;
import com.debao.common.utils.StringUtils;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.domain.UserCard;
import com.debao.system.domain.VipCard;
import com.debao.system.mapper.*;
import com.debao.system.service.IConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.debao.system.domain.VipcardOrder;
import com.debao.system.service.IVipcardOrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 会员卡订单Service业务层处理
 *
 * @author DeBao
 * @date 2024-08-14
 */
@Service
@Slf4j
public class VipcardOrderServiceImpl implements IVipcardOrderService {
    @Autowired
    private VipcardOrderMapper vipcardOrderMapper;


    @Autowired
    private UserCardMapper userCardMapper;

    @Autowired
    private VipCardMapper vipCardMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private ConfigMapper configMapper;

    /**
     * 会员卡开通成功通知模板
     */
    private static final String openTemplateId = "TB-HNaFDqSxbmtykBHQC8zM-YLaWo9tXWUMyr6VT1NQ";
    /**
     * 续费
     */
    private static final String renewTemplateId = "h-Xwztnebkorg2aJPIiRlxNDJxvsNYmHZcicUDWTs9s";

    private static final Object LOCK = new Object();

    /**
     * 查询会员卡订单
     *
     * @param id 会员卡订单主键
     * @return 会员卡订单
     */
    @Override
    public VipcardOrder selectVipcardOrderById(Long id) {
        return vipcardOrderMapper.selectVipcardOrderById(id);
    }

    /**
     * 查询会员卡订单列表
     *
     * @param vipcardOrder 会员卡订单
     * @return 会员卡订单
     */
    @Override
    public List<VipcardOrder> selectVipcardOrderList(VipcardOrder vipcardOrder) {
        return vipcardOrderMapper.selectVipcardOrderList(vipcardOrder);
    }

    /**
     * 根据订单号获取订单信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public VipcardOrder selectVipCardOrderByOrderNo(String orderNo) {
        return vipcardOrderMapper.selectVipcardOrderByOrderNo(orderNo);
    }

    /**
     * 订单是否支付成功
     *
     * @param orderNo
     * @return
     */
    @Override
    public Boolean isPaySuccess(String orderNo) {
        return vipcardOrderMapper.isPaySuccess(orderNo);
    }


    /**
     * 新增会员卡订单
     *
     * @param vipcardOrder 会员卡订单
     * @return 结果
     */
    @Override
    public int insertVipcardOrder(VipcardOrder vipcardOrder) {
        return vipcardOrderMapper.insertVipcardOrder(vipcardOrder);
    }

    /**
     * 修改会员卡订单
     *
     * @param vipcardOrder 会员卡订单
     * @return 结果
     */
    @Override
    public int updateVipcardOrder(VipcardOrder vipcardOrder) {
        return vipcardOrderMapper.updateVipcardOrder(vipcardOrder);
    }

    /**
     * 批量删除会员卡订单
     *
     * @param ids 需要删除的会员卡订单主键
     * @return 结果
     */
    @Override
    public int deleteVipcardOrderByIds(Long[] ids) {
        return vipcardOrderMapper.deleteVipcardOrderByIds(ids);
    }

    /**
     * 删除会员卡订单信息
     *
     * @param id 会员卡订单主键
     * @return 结果
     */
    @Override
    public int deleteVipcardOrderById(Long id) {
        return vipcardOrderMapper.deleteVipcardOrderById(id);
    }


    /**
     * 处理支付成功回调
     *
     * @param orderNo
     * @param transactionId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public void paySucHandleOrder(String orderNo, String transactionId) {
        if (StringUtils.isBlank(orderNo)) {
            log.error("订单数据更新失败，orderNo为空");
            return;
        }
        String logHead = String.format("订单回调更新, orderNo = %s ", orderNo);
        //获取订单信息
        VipcardOrder vipCardOrder = vipcardOrderMapper.selectVipcardOrderByOrderNo(orderNo);
        if (Objects.isNull(vipCardOrder)) {
            // todo 自定义异常类
            log.error(logHead + "订单不存在");
            return;
        }
        if (!StringUtils.equalsIgnoreCase(vipCardOrder.getStatus(), String.valueOf(OrderStatusEnum.None))) {
            log.error(logHead + "订单信息回调已更新 status = {}", vipCardOrder.getStatus());
            return;
        }
        //更新订单状态
        vipCardOrder.setTransactionId(transactionId);
        vipCardOrder.setPayAt(new Date());
        vipCardOrder.setPayMoney(vipCardOrder.getMoney());
        vipCardOrder.setStatus(String.valueOf(OrderStatusEnum.Paid));
        int row = vipcardOrderMapper.updateVipcardOrder(vipCardOrder);
        if (row != 1) {
            log.error(logHead + "订单更新失败");
            return;
        }
        if (row == 1) {
            //用户有没有开通过会员卡
            UserCard userCard = userCardMapper.selectUserCardByUserId(vipCardOrder.getUserId());
            VipCard vipCard = vipCardMapper.selectVipCardById(vipCardOrder.getCardId());
            String phone = userMapper.getPhoneByUserId(vipCardOrder.getUserId());
            String token = configMapper.selectValueByKey(WechatConstants.APP_TOKEN);
            String openId = userMapper.getOpenIdByUserId(vipCardOrder.getUserId());
            String afterAt = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.addDays(new Date(), vipCard.getDuration()));
            //获取当前日期并格式化
            String nowAt = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            if (Objects.isNull(userCard)) {
                //没有开通会员卡，新增会员卡
                String vipNo = "No." + KeyGreaterUtil.getRandom620(6);
                int i = userCardMapper.insertUserCard(new UserCard()
                        .setMemberCard(vipNo)
                        .setUserId(vipCardOrder.getUserId())
                        .setStartAt(String.valueOf(new Date()))
                        .setStartAt(nowAt)
                        .setEndAt(afterAt)
                        .setStatus(VipConstants.NORMAL)
                        .setUserName(SecurityUtils.getNickName())
                        .setPhone(phone));
                //发送消息
                if (i == 1) {
                    Map<String, TempData> data = new HashMap<>();
                    data.put("thing2", new TempData("德宝乒乓球"+vipCard.getName()));
                    data.put("phrase8", new TempData(vipCard.getName()));
                    data.put("time3", new TempData(userCard.getStartAt()));
                    data.put("time4", new TempData(userCard.getEndAt()));
                    //todo 跳转页面 不正确 端页面调整完修改
                    String page ="/subPackages/order/details/order_detail?orderNo=" + orderNo;
                    sendOpenMsg(phone,token,openId ,data,page,openTemplateId);
                }
                return;
            }
            if (userCard.getStatus() == VipConstants.EXPIRE) {
                //用户有会员卡，会员卡已过期,更新会员卡
                userCard.setStartAt(nowAt)
                        .setEndAt(afterAt);
            } else {
                //用户有会员卡，会员卡未过期,延长有效期
                // 新的有效期是 原来的到期时间 + 天数
                String newAfterAt = new SimpleDateFormat("yyyy-MM-dd").format(DateUtils.addDays(DateUtil.parse(userCard.getEndAt(), "yyyy-MM-dd"), vipCard.getDuration()));
                userCard.setEndAt(newAfterAt);
            }
            int result = userCardMapper.updateUserCard(userCard.setStatus(VipConstants.NORMAL));
            if ( result== 1) {
                Map<String, TempData> data = new HashMap<>();
                data.put("thing6", new TempData("德宝东湖昇光店"));
                data.put("thing2", new TempData(vipCard.getName()));
                data.put("character_string7", new TempData(userCard.getMemberCard()));
                data.put("thing5", new TempData("您的会员卡续卡成功，点击查看详情~"));
                //todo 跳转页面 不正确 端页面调整完修改
                String page ="/subPackages/order/details/order_detail?orderNo=" + orderNo;
                sendRenewMsg(phone,token,openId ,data,page,renewTemplateId);
            }

        }
    }

    /**
     * 开通通知
     * @param phone
     * @param token
     * @param openId
     * @param data 模板内容
     * @param page  模板打开的页面
     * @param templateId 模板Id
     */
    public static void sendOpenMsg(String phone, String token, String openId, Map<String, TempData> data, String page, String templateId) {
        //异步方式实现短信推送 通知给平台
        Thread threadMsg = new Thread(() -> {
            synchronized (LOCK) {
                try {
                    if (!phone.isEmpty()) {
                        AliyunSmsUtil.sendSms(phone, "SMS_472420145", null);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (openId.isEmpty()) {
                    return;
                }
                WechatUtils.postTemplateData(new WechatTemplateVo().setTemplateId(templateId).setToken(token).setOpenid(openId).setData(data).setPage(page));
            }
        });
        threadMsg.start();
    }

    /**
     * 续费通知
     * @param phone
     * @param token
     * @param openId
     * @param data 模板内容
     * @param page  模板打开的页面
     * @param templateId 模板Id
     */
    public static void sendRenewMsg(String phone, String token, String openId, Map<String, TempData> data, String page, String templateId) {
        //异步方式实现短信推送 通知给平台
        Thread threadMsg = new Thread(() -> {
            synchronized (LOCK) {
                try {
                    if (!phone.isEmpty()) {
                        AliyunSmsUtil.sendSms(phone, "SMS_472445200", null);
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                if (openId.isEmpty()) {
                    return;
                }
                WechatUtils.postTemplateData(new WechatTemplateVo().setTemplateId(templateId).setToken(token).setOpenid(openId).setData(data).setPage(page));
            }
        });
        threadMsg.start();
    }

}
